<template>
    <div>
        <input id="mapkeyword" v-model="keyword" type="text" @input="getSuggestions" autocomplete="off" :placeholder="placeholder" :style="width">
        <!-- <input id="search" type="button" class="btn" value="搜索" onclick="searchByKeyword()" /> -->
        <ul id="suggestionList">
          <li v-for="item in suggestionList" :key="item.id">
            <a @click="getSelect(item)">{{item.title}}<span class="item_info">（{{item.address}}）</span></a>
          </li>
        </ul>
    </div>
</template>

<script setup>
import {ref,onMounted,nextTick} from "vue"
const props = defineProps({
  width:"",
  region:{
      type:String,
      default:()=>'重庆'
  },
  placeholder:{
    type:String,
    default:()=>'关键字搜索'
  }
})
const emit = defineEmits(['selected'])
onMounted(async ()=>{
    await nextTick()
    init()
})
const keyword = ref('')
const suggest = ref(null)
const suggestionList = ref([])
const init = ()=>{
    suggest.value = new TMap.service.Suggestion({
        // 新建一个关键字输入提示类
        pageSize: 15, // 返回结果每页条目数
        //region: props.region, // 限制城市范围
        //regionFix: true, // 搜索无结果时是否固定在当前城市
    });
}

const getSuggestions = ()=> {
  // 使用者在搜索框中输入文字时触发
  if (keyword.value) {
    suggest.value.getSuggestions({ keyword:keyword.value})
      .then((result) => {
        // 以当前所输入关键字获取输入提示
        console.log("关键字获取输入提示:",result.data)
        suggestionList.value = result.data
      })
      .catch((error) => {
        console.log(error);
      });
  }
}
const getSelect = (item)=>{
  keyword.value = item.title
  emit("selected",item)
  suggestionList.value = []
}

</script>

<style scoped lang="scss">
#suggestionList {
  list-style-type: none;
  padding: 0;
  margin: 0;
  position: relative;
  z-index: 1002;
}

#suggestionList li a {
  margin-top: -1px; 
  background-color: #f6f6f6;  
  text-decoration: none;
  font-size: 12px; 
  color: black; 
  display: block; 
  padding: 3px 8px;
  line-height: normal;
}

#suggestionList li .item_info{
  font-size: 12px;
  color:grey;
}

#suggestionList li a:hover:not(.header) {
  background-color: #eee;
}
#mapkeyword{
  box-sizing: border-box;
  height: 30px;
  padding: 8px;
  border: 1px solid rgba(0, 0, 0, 0.15);
  border-radius: 15px;
  width: 250px;
}
.mapkwStyle{
  #mapkeyword{
    border-radius: 0;
    width: 260px;
  }
}
</style>